package com.cloud.zuul.filter;

import com.cloud.common.utils.JsonUtils;
import com.cloud.zuul.config.security.SecurityFilter;
import com.cloud.zuul.entity.RestEntity;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;

import javax.naming.NoPermissionException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Map;

@Component
public class SecurityZuulFilter extends ZuulFilter {
	static Logger logger = LoggerFactory.getLogger(SecurityZuulFilter.class);

	@Autowired
	private SecurityFilter securityFilter;

	@Override
	public boolean shouldFilter() {
		return true;
	}

	@Override
	public String filterType() {
		return "pre";
	}

	@Override
	public int filterOrder() {
		return 0;
	}

	@Override
	public Object run() throws ZuulException {
		Map<String, String> head = RequestContext.getCurrentContext().getZuulRequestHeaders();
		Boolean error = securityFilter.isAllowAnonymous(head);
        if(error){
			error();
		}
		return null;
	}
    public void error() throws ZuulException {
		try {
			RequestContext ctx = RequestContext.getCurrentContext();
			HttpServletResponse response = ctx.getResponse();
			RestEntity error = RestEntity.error("您没有权限！", 401);
			String errorStr = JsonUtils.serialize(error);
			response.setStatus(ctx.getResponseStatusCode());
			response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
			response.getOutputStream().write(errorStr.getBytes());
		} catch (IOException ex) {
			throw new ZuulException("您没有权限！", 401, "errorCause");
		}
	}
}
